﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Intorise.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Web;
using System.Threading;
using System.Net.Sockets;
using System.Configuration;

namespace Model
{
    public class NewBotEngine : BotEngine
    {
        static readonly string LOGIN_SERVER_URL = ConfigurationManager.AppSettings["LOGIN_SERVER_URL"];

        public NewBotEngine(Player player) : base(player) { }

        public override bool Login()
        {
            string loginUrl = string.Format(LOGIN_SERVER_URL, player.AccountName, player.PlayerAccount.Password, player.ServerID);

            ConsoleBLL.WriteLine(player + " 开始登录...");
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            string html = "";

            try
            {
                request = net.SendRequest(loginUrl, "GET");
                response = (HttpWebResponse)request.GetResponse();
                html = net.GetResponseHtml(response);
            }
            finally
            {
                if (request != null) { request.Abort(); }
                if (response != null) { response.Close(); }
            }

            JObject result = (JObject)JsonConvert.DeserializeObject(html);
            if (infoLog)
            {
                ConsoleBLL.WriteLineInfo(player + " login result:" + result);
            }
            var flag = result["Success"].ToString();
            LoginEntity loginEntity = null;

            if (flag == "True")
            {
                loginEntity = JsonConvert.DeserializeObject<LoginEntity>(result["Data"].ToString());
            }

            if (loginEntity == null || loginEntity.LoginResult != LoginResultEnum.Success)
            {
                return false;
            }

            head = new byte[] { 0x00, 0x01, 0x87, 0x70 };
            serverNo = Tools.GetAscII(player.PlayerAccount.ServerID);
            accountData = Tools.GetAscII(player.PlayerAccount.Username);
            time = Tools.GetAscII(loginEntity.TicketTime);
            singn = Tools.GetAscII(loginEntity.Sign);
            ip = loginEntity.ServerIP;
            port = loginEntity.Port;
            return true;
        }

        public override bool EnterGameServer()
        {
            DateTime startTime = DateTime.Now;
            Client = new TcpClient(ip, 843);
            var data = Tools.GetAscII("<policy-file-request/>\0");
            net.SendData(Client, data);
            Client.Close();

            Client = new TcpClient(ip, port);
            Begin();

            data = Tools.Contact(head, DataPackager.GetNetworkData((short)serverNo.Length), serverNo, net.GetNetworkBytes((short)accountData.Length), accountData, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A }
                , time, new byte[] { 0x00, 0x01, 0x31, 0x00, 0x20 }, singn
                , new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x75, 0x6E, 0x64, 0x65, 0x66, 0x69, 0x6E, 0x65, 0x64, 0x00, 0x00 });
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            net.SendData(Client, data, data.Length);

            while (!player.Entered)
            {
                Thread.Sleep(500);
                if (player.Config.TimeoutLogin < (DateTime.Now - startTime).TotalSeconds) { break; }
            }

            if (!player.Entered)
            {
                ConsoleBLL.WriteLineWaring(player + " 进入游戏超时！");
                Stop();
            }
            return player.Entered;
        }
    }
}
